#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "model/tablemodel.h"
#include "delegate/comboboxdelegate.h"
#include "delegate/progressbardelegate.h"
#include "delegate/checkboxdelegate.h"
#include "delegate/buttondelegate.h"

#include <QProgressBar>
#include <QHeaderView>
#include <QMessageBox>
#include <QFileDialog>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_model(new TableModel(this))
{
    ui->setupUi(this);
    // m_model->setVerticalHeaders(QStringList() << "1"<<"2"<<"3");
    m_model->setHorizontalHeaders(TableRowItem::horizonalHeaderNames());
    ui->tableView->setModel(m_model);

    ComboBoxDelegate *combo = new ComboBoxDelegate(TableRowItem::gradeNames(), this);
    ui->tableView->setItemDelegateForColumn(TableRowItem::Grade, combo);

    ui->tableView->setItemDelegateForColumn(TableRowItem::Progress, new ProgressBarDelegate(this));
    ui->tableView->setItemDelegateForColumn(TableRowItem::Checked, new CheckBoxDelegate(this));

    ButtonDelegate *button = new ButtonDelegate(tr("Open..."), this);
    connect(button, &ButtonDelegate::clicked, this, [=](int row) {
        QString fileName = QFileDialog::getSaveFileName(this, tr("Save file"), qApp->applicationDirPath());
        if(!fileName.isEmpty()) {
            m_model->setData(m_model->index(row, TableRowItem::Path), fileName);
            QMessageBox::information(this, "Tip", tr("Row %1 set file name %2").arg(row).arg(fileName));
        }
    });
    ui->tableView->setItemDelegateForColumn(TableRowItem::Path, button);

    ui->tableView->setSelectionMode(QTableView::SingleSelection);
    ui->tableView->setSelectionBehavior(QTableView::SelectRows);
    // ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->tableView->horizontalHeader()->setSectionResizeMode(TableRowItem::Progress, QHeaderView::Stretch);

    connect(ui->tableView->selectionModel(), &QItemSelectionModel::currentRowChanged, this,
            [=](const QModelIndex &current, const QModelIndex &previous) {
        qDebug() << QString("previous: (%1, %2)").arg(previous.row()).arg(previous.column());
        qDebug() << QString("current: (%1, %2)").arg(current.row()).arg(current.column());
        ui->btnRemove->setEnabled(current.row() >= 0 && current.row() < m_model->rowCount());
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btnAdd_clicked()
{
    m_model->appendRow(TableRowItem {300, "xiaohong", 2, 65, false});
}


void MainWindow::on_btnRemove_clicked()
{
    int row = ui->tableView->currentIndex().row();
    qDebug() << "Remove row: " << row;
    if(row >= 0 && row < m_model->rowCount())
        m_model->removeRow(ui->tableView->currentIndex().row());
}


void MainWindow::on_btnClear_clicked()
{
    m_model->clear();
}


void MainWindow::on_btnSort_clicked()
{

}

